/*
 * 账户管理
 * @author 狮子
 * @time 2018/11/9
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import {Col, Form, Modal, Row,} from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
import cx from 'classnames'
// 引入model取值工具方法 
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
//权限管理
import FlagBtn from 'widget/FlagBtn/FlagView'
import styles from './accountListStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import Uploader from "widget/Upload";
import {cloneDeep} from "lodash";

const confirm = Modal.confirm;

const  FormItem = Form.Item
let newBannerList_default=[{
    "url": "",
    "href": "",
    "type": 1,
    "ord": '',
    "published": '0',
    "channel": 101,
    "title": '轮播图',
}]

const routeView = function ({ dispatch, model, form }) {

    const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
    const {modelObj, namespace} = model
    let {areaList, option,visible,imgUrl,uploadFileObj,fileUrl,imageUrls,biz,area1,products, areas} = modelObj
console.log(modelObj)
    // 资讯详情页跳转
    function detailSkip(type, id = '') {
        hashHistory.push({
            pathname: '/home/accountAdmin/accountDetail',
            query: {actionType: type, id}
        });
    }

    //导出
    function down() {
        dispatch({
            type: `${namespace}/down`,
            payload: {}
        });
    }

    const changeState = (payload) => {
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { ...payload }
        })
    }
    function updateImageModel(value,fileObj) {
        console.log('updateImageModel',value,fileObj)
        imageUrls[0]={
            url:value,
            name:fileObj.name,
        };
        // 分发到model
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { imageUrls }
        })
    };

    function removeImgUrl(index) {

        imageUrls.splice(index, 1)
        dispatch({
            type: `${namespace}/updateStore`,
            payload: { imageUrls }
        })
    }
//导入
    function updateUploadModal(){
        uploadFileObj.visible=!uploadFileObj.visible
        changeState({uploadFileObj})
    }

  let pageProps = {
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      api_url: "admin/bankAccount/queryList",
      // 接口方式
      method: "POST",
      headers: {
        "Content-type": "application/json"
      },
      app: "",
      // 接口参数
      params: "pageNo=1&pageSize=10",
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
            {
              en_name: 'regionId',
              zh_name: '所属区域',
              elem_type: 'Select',
              elem_valid_type: 'string',
                //关联的更改的搜索字段
              cmpt_items:area1,
           },
           {
            en_name: 'province',
            zh_name: '所属城市',
            elem_type: 'Cascader',
            elem_valid_type: 'string',
            changeOnSelect:true,
            cmpt_items: areas,
            split_keys: ['province', 'city'],
            onFocus:()=>{
              area1.map((item,index)=>{
                console.log(biz.queryForm.regionId,item.value)
                if(biz.queryForm && biz.queryForm.regionId && biz.queryForm.regionId==item.value)
                {
                  console.log(biz.queryForm.regionId,item.value)
                  dispatch({
                    type: `${namespace}/updateStore`,
                    payload:{
                      areas:item.children,
                    }
                  })
                }
              })
            },
          },
           {
              en_name: 'productId',
              zh_name: '项目名称',
              elem_type: 'Select',
              elem_valid_type: 'string',
              // showSearch:true,
              cmpt_items:products,
              onFocus:()=>{
                console.log(biz.queryForm,biz.queryForm.city)
                if(biz.queryForm && biz.queryForm.city)
                { 
                  dispatch({
                    type: `${namespace}/getProduct`,
                    payload:{
                      cityCode:biz.queryForm.city,
                    }
                  })
                }
              },
            },
            {
              en_name: 'accountName',
              zh_name: '账户名称',
              elem_type: 'Input',
              elem_valid_type: 'string',
            },
          
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click',e)
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      "table":
        {
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 1700 },
          fields: [
            {
              en_name: "key",
              zh_name: "序号",
              width: 60,
              render: (a, item, index, d, e, f) => {
                return index+1
              },
            },
            {
              en_name: "productId",
              zh_name: "项目编号",
            },
            {
              en_name: "name",
              zh_name: "项目名称",
              width:250,
            },
            {
              en_name: "cityName",
              zh_name: "所属城市",
              width:250,
              render:(a, item, index, d, e, f) => {
                return `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||' '}${item.cityName||''}`
              }
            },
            {
              en_name: "regionName",
              zh_name: "所属区域",
              width:250,
            },
            {
              en_name: "accountName",
              zh_name: "账户名称",
            },
            {
              en_name: "bankAccount",
              zh_name: "银行账号",
            },
            {
              en_name: 'accountType',
              zh_name: '账户类型',
              render: () => {
                return '公户'
              }
            },
            {
              en_name: "bankAccountName",
              zh_name: "开户支行",
              width:150,
            },
            {
              en_name: "createPerson",
              zh_name: "创建人",
              width:90
            },
            {
              en_name: "createTime",
              zh_name: "创建时间",
              width:180,
            },
            {
              en_name: "updatePerson",
              zh_name: "更新人",
              width:90
            },
            {
              en_name: "updateTime",
              zh_name: "更新日期",
              width:180
            },
            {
              en_name: "edit",
              zh_name: "操作",
              width:160,
              fixed:'right',
              render: (a, item, index, d, e, f) => {
                return (
                  <span>
                    <FlagBtn node={ <a onClick={() => detailSkip('check', item.productBankAccountId)}>查看<span className="ant-divider" /></a>}
                    btnId={'140101'}
                    />
                    <FlagBtn node={ <a onClick={() => detailSkip('edit', item.productBankAccountId)}>编辑<span className="ant-divider" /></a>}
                    btnId={'140102'}
                    />
                    <FlagBtn node={ <a onClick={() => showDeleteConfirm(item.productBankAccountId)} >删除</a>}
                    btnId={'140103'}
                    />
                  </span>
                )
              },
            },
          ]
        },
        action_bar:[{
            label: "导出模板",
            btnId:'140104',
            type: "primary",
            onClick: (e) =>{
                down()
            }
        },{
          label:'导入',
          type:'primary',
          btnId:'140105',
          onClick:(e,row)=>{
              updateUploadModal()
            //console.log()
            //detailSkip("add")
          }
        },{
        label:'新建项目银行账户',
        type:'primary',
        btnId:'140106',
        onClick:(e,row)=>{
          //console.log()
          detailSkip("add")
        }
      }]
    },
  }
  function showDeleteConfirm(id) {
      confirm({
        title: '删除确认',
        content: '您真的要删除此条账户信息吗?',
        okText: '确认',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          dispatch({
            type: `${namespace}/deleteData`,
            payload:{
              id,
            }
          })
        },
        onCancel() {
          console.log('Cancel');
        },
      });
  }
  if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
      //console.log(biz)
			dispatch({
				type: `${namespace}/updateStore`,
				payload: { biz }
			})
		}
	}
  return (
    <div className={cx('pageLayout')}>
        <Modal title={'导入账户列表'}
               visible={uploadFileObj.visible}
               okText={'导入'}
               cancelText={'取消'}
               confirmLoading={uploadFileObj.confirmLoading}
               onCancel={(e) => {
                   updateUploadModal()
               }}
               onOk={(e) => {
                   dispatch({
                       type: `${namespace}/importAccount`,
                       payload: {}
                   });
                   // dispatch({
                   //     type: `${namespace}/updateStore`,
                   //     payload: { visible:!visible }
                   // });
               }}
               width={720}>
            <div className={styles.modalCss}>
                <Form>
                    <Row>
                        <Col span={24}>
                            <FormItem label={'文件'}>
                                <Uploader
                                    uploadedUrls={imageUrls}
                                    removeFileCbf={(index) => { removeImgUrl(index) }}
                                    uploadSuccessCbf={(imgUrl,fileObj) => { updateImageModel(imgUrl,fileObj) }}
                                    showType='5'
                                    accept={'.xlsx,.xls'}
                                    uploadTip='支持*.xlsx, *.xls格式文件。'
                                    fileType='file'
                                    maxFiles='50'
                                />
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        </Modal>
      <ListPage pageProps={pageProps} />
    </div>
  )
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(routeView))
